public class RationalNumber
{
    private int numerator, denominator;
    //  构造函数：通过确保一个非零的分母和唯一的分子来设置合理的分数。
    public RationalNumber (int numer, int denom)
    {
        if (denom == 0)
            denom = 1;
        // Make the numerator "store" the sign
        if (denom < 0)
        {
            numer = numer * -1;
            denom = denom * -1;
        }
        numerator = numer;
        denominator = denom;
        reduce();
    }

    // 返回有理数的分子
    public int getNumerator ()
    {
        return numerator;
    }

    //  返回有理数的分母
    public int getDenominator ()
    {
        return denominator;
    }

    //  返回这个有理数的倒数.
    public RationalNumber reciprocal ()
    {
        return new RationalNumber (denominator, numerator);
    }

    //真分数的加法
    // 添加此有理数作为参数传递，两个独立的分母相乘得到一个共同的分母
    public RationalNumber add (RationalNumber op2)
    {
        int commonDenominator = denominator * op2.getDenominator();
        int numerator1 = numerator * op2.getDenominator();
        int numerator2 = op2.getNumerator() * denominator;
        int sum = numerator1 + numerator2;

        return new RationalNumber (sum, commonDenominator);
    }

    //  真分数的减法

    public RationalNumber subtract (RationalNumber op2)
    {
        int commonDenominator = denominator * op2.getDenominator();
        int numerator1 = numerator * op2.getDenominator();
        int numerator2 = op2.getNumerator() * denominator;
        int difference = numerator1 - numerator2;

        return new RationalNumber (difference, commonDenominator);
    }

    //  真分数的乘法
    public RationalNumber multiply (RationalNumber op2)
    {
        int numer = numerator * op2.getNumerator();
        int denom = denominator * op2.getDenominator();

        return new RationalNumber (numer, denom);
    }

    //  真分数的除法
    //  通过乘以参数的倒数
    public RationalNumber divide (RationalNumber op2)
    {
        return multiply (op2.reciprocal());
    }

    //  判断是否相等
    public boolean isLike (RationalNumber op2)
    {
        return ( numerator == op2.getNumerator() &&
                denominator == op2.getDenominator() );
    }

    //将有理数转换为字符
    public String toString ()
    {
        String result;

        if (numerator == 0) {
            result = "0";
        }
        else {
            if (denominator == 1)
                result = numerator + "";
            else
                result = numerator + "/" + denominator;
        }
            return result;
    }

    // 化简真分数使其分子与分母互素
    private void reduce ()
    {
        if (numerator != 0)
        {
            int common = gcd (Math.abs(numerator), denominator);

            numerator = numerator / common;
            denominator = denominator / common;
        }
    }

    //  求最大公因子
    private int gcd (int num1, int num2)
    {
        while (num1 != num2)
            if (num1 > num2)
                num1 = num1 - num2;
            else
                num2 = num2 - num1;

        return num1;
    }
}